package cn.ncist.health_backend.config;

import cn.ncist.health_backend.service.SpringSecurityUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * @Author shier
 * @Date 2022/9/5 14:39
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;//没有权限
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;//登录成功

    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;//登录失败

    private static final String[] URl_WHITELIST={
            "/login.html",
            "/templates/css/**",
            "/templates/img/**",
            "/templates/js/**",
            "/templates/plugins/**",
            "/tologin",
            "/swagger-ui.html",
            "/v2/**",
            "/swagger-resources/**",
            "/webjars/**",
            "/doc.html",

    };

    @Autowired
    private SpringSecurityUserService springSecurityUserService;

    @Bean
    BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(springSecurityUserService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors().and().csrf().disable()
                // 配置请求地址的权限
                .authorizeRequests()
                .antMatchers(URl_WHITELIST).permitAll() // 所有用户可以访问
                .antMatchers("/pages/**").access("isAuthenticated()")
                // 任何请求，访问的用户都需要经过认证
                .anyRequest().authenticated()
                .and().exceptionHandling()
                .accessDeniedHandler(accessDeniedHandler)
                .and()
                .formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler(authenticationSuccessHandler)//成功处理器
                .failureHandler(authenticationFailureHandler)//失败处理器
                .loginPage("/templates/login.html")
                .loginProcessingUrl("/tologin")
                .defaultSuccessUrl("/templates/pages/main.html",true)
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/tologout")
                .logoutSuccessUrl("/login.html")
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .and()
                .headers().frameOptions().sameOrigin();
    }
}
